#include "ConvertUtil.h"
//#include <objLoader.h>
#include "objLoader.h"
#include <string>

using namespace std;

string model;

typedef struct{
	int s;
	int e;
} Dir;

void conversionFromObj( Edge** edgeList, Vert** vertList, Face** faceList, int* faceCount, int* vertCount )
{
	char* cstr = new char[model.length() + 1];
	strcpy(cstr, model.c_str());

	objLoader *objdata;
	objdata = new objLoader();	
	objdata->load(cstr);

	printf("hello");

	delete cstr;

	vector<Dir>* tmpEdgeList = new vector<Dir>();
	*vertList = (Vert*)malloc(objdata->vertexCount * sizeof(Vert));
	*faceList = (Face*)malloc(objdata->faceCount * sizeof(Face));
	*edgeList = (Edge*)malloc(objdata->faceCount * 3 * sizeof(Edge));

	*faceCount = objdata->faceCount;
	*vertCount = objdata->vertexCount;

	for (int i=0; i<objdata->faceCount; i++)
	{
		obj_face* f = objdata->faceList[i];
		Dir v;
		Edge he_e;

		v.s = f->vertex_index[0];
		v.e = f->vertex_index[1];
		tmpEdgeList->push_back(v);
		he_e.face = i;
		he_e.next = i * 3 + 1;
		he_e.vert = v.s;
		(*edgeList)[i*3+0] = he_e;

		v.s = f->vertex_index[1];
		v.e = f->vertex_index[2];
		tmpEdgeList->push_back(v);
		he_e.face = i;
		he_e.next = i * 3 + 2;
		he_e.vert = v.s;
		(*edgeList)[i*3+1] = he_e;

		v.s = f->vertex_index[2];
		v.e = f->vertex_index[0];
		tmpEdgeList->push_back(v);
		he_e.face = i;
		he_e.next = i * 3 + 0;
		he_e.vert = v.s;
		(*edgeList)[i*3+2] = he_e;

		Face he_f;
		he_f.edge = i * 3;

		(*faceList)[i] = he_f;
	}

	for (int i=0; i<objdata->vertexCount; i++)
	{
		obj_vector* v = objdata->vertexList[i];
		Vert he_v;

		he_v.x = v->e[0];
		he_v.y = v->e[1];
		he_v.z = v->e[2];

		for (int j=0; j<tmpEdgeList->size(); j++)
		{
			Dir d = tmpEdgeList->at(j);

			if (d.s == i)
			{
				he_v.edge = j;
				break;
			}
		}

		(*vertList)[i] = he_v;
	}

	for (int i=0; i<tmpEdgeList->size(); i++)
	{
		Dir d0 = tmpEdgeList->at(i);

		for (int j=0; j<tmpEdgeList->size(); j++)
		{
			Dir d1 = tmpEdgeList->at(j);

			if (d0.s == d1.e && d0.e == d1.s)
			{
				(*edgeList)[i].pair = j;
				(*edgeList)[j].pair = i;
				break;
			}
		}
	}

	tmpEdgeList->clear();

	delete tmpEdgeList;
	delete objdata;
}
